import React, { useState, useEffect } from 'react';
import styled, { keyframes, css } from 'styled-components';
import { Card } from 'antd';
import { useTypewriter } from '../hooks/useTypewriter';
import { API_BASE_URL } from '../config';
import { playAudioByIndex } from '../utils/audioPlayer';
import { quickMessages } from '../types/messages';

// 添加浮动动画
const float = keyframes`
  0% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(5deg); }
  100% { transform: translateY(0px) rotate(0deg); }
`;

// 添加脉冲动画
const pulse = keyframes`
  0% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.1); opacity: 0.8); }
  100% { transform: scale(1); opacity: 1; }
`;

// 添加背景动画
const gradientMove = keyframes`
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
`;

// 添加星星闪烁动画
const twinkle = keyframes`
  0% { opacity: 0.2; transform: scale(0.8); }
  50% { opacity: 1; transform: scale(1.2); }
  100% { opacity: 0.2; transform: scale(0.8); }
`;

// 删除 orbit 动画，添加新的动画效果
const ripple = keyframes`
  0% { transform: scale(1); opacity: 0.4; }
  100% { transform: scale(2.5); opacity: 0; }
`;

const rotate = keyframes`
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
`;

const scaleAnimation = keyframes`
  0% { transform: scale(0); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
`;

const shake = keyframes`
  0% { transform: translate(0, 0) rotate(0deg); }
  25% { transform: translate(-1px, -1px) rotate(-0.5deg); }
  50% { transform: translate(1px, 1px) rotate(0.5deg); }
  75% { transform: translate(-1px, 1px) rotate(-0.5deg); }
  100% { transform: translate(0, 0) rotate(0deg); }
`;

const PageContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 50px;
  min-height: 80vh;
  position: relative;
  background: linear-gradient(-45deg, #002FA7, #1A237E, #304FFE, #0091EA);
  background-size: 400% 400%;
  animation: ${gradientMove} 15s ease infinite;
`;

// 几何装饰元素
const GeometricShape = styled.div`
  position: absolute;
  border: 2px solid rgba(0, 47, 167, 0.1);
  animation: ${float} 6s ease-in-out infinite;
  opacity: 0.1;
  
  &.circle {
    width: 200px;
    height: 200px;
    border-radius: 50%;
    top: 10%;
    left: 10%;
    animation-delay: 0s;
  }
  &.square {
    width: 150px;
    height: 150px;
    transform: rotate(45deg);
    bottom: 15%;
    right: 15%;
    animation-delay: 2s;
  }
  &.triangle {
    width: 0;
    height: 0;
    border-left: 100px solid transparent;
    border-right: 100px solid transparent;
    border-bottom: 173.2px solid rgba(0, 47, 167, 0.05);
    top: 20%;
    right: 20%;
    animation-delay: 4s;
  }
`;

const EmojiContainer = styled.div`
  width: 500px;  // 进一步增加宽度
  height: 500px; // 进一步增加高度
  border-radius: 50%;
  background: linear-gradient(45deg, #002FA7 0%, #1A237E 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 200px;  // 进一步增大表情大小
  margin-bottom: 40px;  // 增加间距
  box-shadow: 0 8px 24px rgba(0,47,167,0.25);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1;
  position: relative;
  background: linear-gradient(-45deg, #002FA7, #1A237E, #304FFE, #0091EA);
  background-size: 400% 400%;
  animation: ${gradientMove} 10s ease infinite;
  
  &::before {
    content: '';
    position: absolute;
    top: -5px;
    left: -5px;
    right: -5px;
    bottom: -5px;
    border-radius: 50%;
    background: linear-gradient(45deg, #FF5252, #FF1744);
    z-index: -1;
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  
  &:hover::before {
    opacity: 1;
  }

  &:hover {
    transform: translateY(-5px) scale(1.02);
  }
`;

const EmojiContent = styled.div`
  animation: ${css`${scaleAnimation} 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)`};
`;

const DialogCard = styled(Card)<{ $isTyping: boolean }>`
  width: 95%;  // 增加宽度占比
  max-width: 1000px;  // 增加最大宽度
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 2px solid #002FA7;
  border-radius: 15px;
  padding: 40px;  // 增加内边距
  font-size: 36px;  // 进一步增大字体
  text-align: center;
  z-index: 1;
  transform-style: preserve-3d;
  transition: transform 0.5s ease;
  animation: ${props => props.$isTyping ? css`${shake} 0.2s ease-in-out infinite` : 'none'};
  
  &:hover {
    transform: translateZ(20px);
  }
  
  .ant-card-body {
    padding: 40px;
    font-size: 36px;
    line-height: 2;
  }
`;

// 添加波纹效果组件
const RippleEffect = styled.div`
  position: absolute;
  width: 300px;
  height: 300px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  animation: ${ripple} 3s ease-out infinite;
  
  &:nth-child(2) {
    animation-delay: 1s;
  }
  
  &:nth-child(3) {
    animation-delay: 2s;
  }
`;

// 添加DNA双螺旋效果
const DNAStrand = styled.div`
  position: absolute;
  left: 10%;
  height: 80%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  animation: ${rotate} 20s linear infinite;
  
  &::before, &::after {
    content: '';
    position: absolute;
    width: 8px;
    height: 8px;
    background: rgba(255, 255, 255, 0.6);
    border-radius: 50%;
    animation: ${pulse} 2s ease-in-out infinite alternate;
  }
  
  &::before {
    left: -20px;
    animation-delay: 0s;
  }
  
  &::after {
    right: -20px;
    animation-delay: 1s;
  }
`;

// 添加能量光环
const EnergyRing = styled.div`
  position: absolute;
  width: 320px;
  height: 320px;
  border-radius: 50%;
  background: linear-gradient(45deg, transparent 40%, rgba(255, 255, 255, 0.3));
  animation: ${rotate} 8s linear infinite;
  
  &::before {
    content: '';
    position: absolute;
    inset: -5px;
    border-radius: 50%;
    background: linear-gradient(-45deg, transparent 40%, rgba(255, 255, 255, 0.2));
    animation: ${rotate} 5s linear infinite reverse;
  }
`;

// 为Star组件添加类型定义
interface StarProps {
  delay?: string;
}

const Star = styled.div<StarProps>`
  position: absolute;
  width: 4px;
  height: 4px;
  background: white;
  border-radius: 50%;
  animation: ${twinkle} ${props => props.delay || '3s'} ease-in-out infinite;
`;

const CommunicationRoom: React.FC = () => {
  const [currentEmoji, setCurrentEmoji] = useState('🤖');
  const [message, setMessage] = useState('');
  const [animationKey, setAnimationKey] = useState<number>(0); // 添加animationKey状态
  const { text, isTyping, cursor } = useTypewriter(message, {
    speed: 50,
    cursor: true,
  });

  // 获取后端状态
  useEffect(() => {
    const fetchState = async () => {
      try {
        const response = await fetch(`${API_BASE_URL}/api/state`);
        const data = await response.json();
        if (data.emoji && data.emoji !== currentEmoji) {
          setAnimationKey((prev: number) => prev + 1);
          setCurrentEmoji(data.emoji);
        }
        if (typeof data.message === 'string') {
          const newMessage = data.message.trim();
          if (newMessage !== message) {
            setMessage(newMessage);
            const matchedMessage = quickMessages.find(item => item.text === newMessage);
            if (matchedMessage) {
              playAudioByIndex(matchedMessage.audioIndex);
            }
          }
        }
      } catch (error) {
        console.error('获取状态失败:', error);
      }
    };

    fetchState();
    const interval = setInterval(fetchState, 1000);
    return () => clearInterval(interval);
  }, [message, currentEmoji]);

  // 生成随机位置的星星
  const stars = Array.from({ length: 20 }, (_, i) => ({
    id: i,
    top: `${Math.random() * 100}%`,
    left: `${Math.random() * 100}%`,
    delay: `${Math.random() * 3 + 1}s`
  }));

  return (
    <PageContainer>
      {/* 添加波纹效果 */}
      <RippleEffect />
      <RippleEffect />
      <RippleEffect />
      <DNAStrand />
      <EnergyRing />
      
      {/* 添加装饰星星 */}
      {stars.map(star => (
        <Star
          key={star.id}
          style={{
            top: star.top,
            left: star.left,
            animationDelay: star.delay
          }}
        />
      ))}
      
      <GeometricShape className="circle" />
      <GeometricShape className="square" />
      <GeometricShape className="triangle" />
      <EmojiContainer>
        <EmojiContent key={animationKey}>
          {currentEmoji}
        </EmojiContent>
      </EmojiContainer>
      <DialogCard $isTyping={isTyping}>
        <p style={{ minHeight: '2em', margin: 0, padding: '20px' }}>
          {text}
          {cursor && <span className="cursor">|</span>}
        </p>
      </DialogCard>
    </PageContainer>
  );
};

export default CommunicationRoom;
